package com.tzxs.pay.main.mine.viewmodel;

import android.app.Application;
import android.util.Log;

import com.tzxs.pay.main.login.model.User;
import com.tzxs.pay.util.ISharedPreference;
import com.tzxs.pay.util.RetrofitUtil;
import com.tzxs.pay.util.RxUtil;
import com.tzxs.pay.util.netnavigator.NetNavigator;
import com.tzxs.pay.util.netnavigator.NetNavigatorWrapper;

import java.lang.ref.WeakReference;

//个人中心
public class MineDataResource {
    private static final String TAG = MineDataResource.class.getSimpleName();
    private static MineDataResource instance;
    //采用弱引用
    private WeakReference<Application> weakApp;

    private MineDataResource(WeakReference<Application> weakApp) {
        this.weakApp = weakApp;
    }

    public static MineDataResource getInstance(Application application) {
        if (instance == null) {
            synchronized (MineDataResource.class) {
                if (instance == null) {
                    instance = new MineDataResource(new WeakReference<>(application));
                }
            }
        }
        return instance;
    }


    //获取用户信息
    public void getUserInfo(String token, final NetNavigator<User> netNavigator) {
        NetNavigatorWrapper<User> netNavigatorWrapper = new NetNavigatorWrapper<User>(netNavigator) {
            @Override
            public void success(User data) {
                super.success(data);
                //保存用户相关信息

                Log.d(TAG, "success: 获取用户信息成功!");
                String phone = data.getData().getPhone();
                int userId = data.getData().getId();
                String userName = data.getData().getName();

                ISharedPreference sharedPreference = ISharedPreference.getInstance(weakApp.get());
                sharedPreference.saveUserId(userId);
                sharedPreference.savePhone(phone);
                sharedPreference.saveUserName(userName);

                netNavigator.success(data);
            }

            @Override
            public void fail(String error) {
                super.fail(error);
                Log.d(TAG, "fail: 获取用户信息失败:" + error);
            }
        };
        RxUtil.ioMain(RetrofitUtil.getInstance().apiService.getUserInfo(token), netNavigatorWrapper);

    }
}
